package com.nineclock.message.service.impl;

import com.nineclock.message.config.JPushManager;
import com.nineclock.message.service.MessageService;
import com.nineclock.system.message.dto.NcMessageDTO;
import com.nineclock.system.message.pojo.NcMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class MessageServiceImpl implements MessageService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    JPushManager jPushManager;
    @Override
    public void pushSingleMessage(NcMessage message) throws Exception {
        //存储消息到MongoDB中
        mongoTemplate.save(message);

        //推送消息给管理员
        jPushManager.sendNotificationByAlias(message.getTitle(), message.getContent(), message.getTargets(), null);
    }

    @Override
    public List<NcMessage> findMessageRecord(NcMessageDTO messageDTO) {
        Query query = new Query();
//where 列 is ：具体的值
        // column = 1
        if(messageDTO.getId() != null){
            query.addCriteria(Criteria.where("_id").is(messageDTO.getId()));
        }

        if(messageDTO.getType() != null){
            query.addCriteria(Criteria.where("messageType").is(messageDTO.getType()));
        }

        if(messageDTO.getUserId() != null){
            query.addCriteria(Criteria.where("applyUserId").is(messageDTO.getUserId()));
        }

        if(messageDTO.getTargetId() != null){
            query.addCriteria(Criteria.where("approveUserId").is(messageDTO.getTargetId()));
        }

        //排序, 根据审核状态升序排序（必须排序，否则会不显示）
        query.with(Sort.by(Sort.Direction.ASC, "approveStatue"));


        List<NcMessage> messageList = mongoTemplate.find(query, NcMessage.class);
        return messageList;
    }

    @Override
    public void updateMessage(String messageId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(messageId));

        Update update = new Update();
        update.set("useStatus",1);
        update.set("approveStatue",1);
        update.set("title","团队申请通过");

        mongoTemplate.updateFirst(query,update,NcMessage.class);
    }


}
